package cloud.component;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author: mengxiangzhong
 * @date: 2023/3/31 9:49
 * @TODO: 分布式所工具
 **/

public class RedissonComponent {

    private RedissonClient redissonClient;

    public RedissonComponent(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 加锁
     * @param lockKey
     * @return
     */
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * 加锁-超时（时间单位：秒）
     * @param lockKey
     * @param leaseTime
     * @return
     */
    public RLock lock(String lockKey, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * 加锁-超时
     * @param lockKey
     * @param unit
     * @param timeout
     * @return
     */
    public RLock lock(String lockKey, TimeUnit unit, int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
        return lock;
    }

    /**
     * 加锁
     * @param lockKey
     * @param unit
     * @param waitTime
     * @param leaseTime
     * @return
     */
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 解锁
     * @param lockKey
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    /**
     * 解锁
     * @param lock
     */
    public void unlock(RLock lock) {
        lock.unlock();

    }


    /**
     * 解锁
     * @param lockKey
     * @throws Exception
     */
    public void unlockWithTime(String lockKey) throws Exception {
        RLock lock = redissonClient.getLock(lockKey);
        unlockWithTime(lock);
    }

    /**
     * 解锁
     * @param lock
     * @throws Exception
     */
    public void unlockWithTime(RLock lock) throws Exception {
        if(lock.isExists()) {
            lock.unlock();
            return ;
        }
        throw new Exception("this redis lock has bean unlocked");
    }

}
